<template>
    <div class="container">
        <div class="use-address">
            <div class="header">
                <div class="left">收货信息:</div>
                <div class="right" @click="showModal=true">
                    <i class="iconfont icon-bianji"></i>
                    <span class="text">编辑收货信息</span>
                </div>
            </div>
            <div class="address">
                <i class="iconfont icon-daohangdizhi"></i>
                <span class="text">
                    {{ community_name + point_name + point_address + roomNo }}
                </span>
            </div>
            <div class="user">
                <i class="iconfont icon-fl-renyuan"></i>
                <span class="name">{{consignee}}</span>
                <span class="phone">{{phone}}</span>
            </div>
        </div>
        <div class="goods-detail">
            <div class="header">商品信息</div>
            <div class="goods-content">
                <div class="good" v-for="(good,index) in order" :key="index">
                    <img class="img" :src="'http://47.104.186.142:8000/'+good.image">
                    <div class="content">
                        <div class="title">
                            {{good.name}}
                        </div>
                        <div class="describe">
                            {{good.remarks}}
                        </div>
                        <div class="price-number">
                            <div class="price">￥{{good.price|numFilter(2)}}</div>
                            <div class="number">X{{good.number}}</div>
                        </div>
                    </div>
                </div>
            </div>
            <div class="goods-footer">
                <div class="discount-price">
                    <span class="text">优惠金额：</span>
                    <span class="price">￥0.00</span>
                </div>
                <div class="discount-coupon">
                    <span class="text">0张可用</span>
                    <i class="iconfont icon-jiantouyou"></i>
                </div>
            </div>
        </div>
        <div class="footer">
            <div class="totle">合计： ￥{{totlePrice|numFilter(2)}}</div>
            <div class="ordering" @click="gotoPay"> 去付款 </div>
        </div>

        <!-- 编辑收货信息模态框 -->
        <modal class="modal" v-if="showModal" @close="cancelAddress">
            <h3 class="modal-title" slot="header">
                编辑收货信息
            </h3>
            <div class="modal-center" slot="body">
                <form>
                    <div class="form-group">
                        <label>配送社区</label>
                        <input type="text" :value="community_name" disabled>
                    </div>
                    <div class="form-group">
                        <label>配送点</label>
                        <input type="text" :value="point_name+point_address" disabled>
                    </div>
                    <div class="form-group">
                        <label>房间号</label>
                        <input type="text" v-model="roomNo">
                    </div>
                    <div class="form-group">
                        <label>收货人</label>
                        <input type="text" v-model="consignee">
                    </div>
                    <div class="form-group">
                        <label>联系电话</label>
                        <input type="text" v-model="phone">
                    </div>
                </form>
            </div>
            <div class="modal-foot" slot="footer">
                <button type="button" class="btn button-cancel" @click="cancelAddress">
                    取消
                </button>
                <button type="button" class="btn button-submit" @click="submitAddress">
                    确认
                </button>
            </div>
        </modal>

        <!-- 验证不能为空提示模态框 -->
        <modal class="modal" v-if="showModal2" @close="showModal2 = false">
            <span slot="header"></span>
            <span slot="body">{{message}}</span>
            <div slot="footer">
                <button class="modal-default-button" @click="checkShowModal">
                    OK
                </button>
            </div>
        </modal>
    </div>
</template>

<script type="text/ecamscript-6">
import { getAddressList } from "@/api/address";
import Bus from "@/commom/js/bus";
import numFilter from "@/commom/js/numFilter";
import modal from "@/base/modal/modal";
import currentdate from "@/commom/js/currentDate";
import axios from "axios";

export default {
  data() {
    return {
      order: [],
      userAddress: [],
      showModal: false,
      showModal2: false,
      point_name: "",
      point_address: "",
      community_name: "",
      roomNo: "",
      consignee: "",
      phone: "",
      megssage: "",
      totlePriceTemp: "",
      openId: "",
      order_num: "",
      showUserModal: "",
      showModal2Type: "" //弹框2验证类型，如果需要弹出弹框1，type类型
    };
  },
  components: {
    modal
  },
  computed: {
    totlePrice() {
      let totlePrice = 0;
      this.order.forEach(item => {
        totlePrice += item.number * item.price;
      });
      this.totlePriceTemp = totlePrice;
      return totlePrice;
    }
  },
  filters: {
    numFilter
  },
  created() {
    //商品订单信息从上个页面菜谱详情中存的order临时数组中获取
    this.order = Bus.order;

    // 从本地localstorage中获取用户的OpenId
    this.openId = localStorage.getItem("setOpenId");

    if (!sessionStorage.getItem("setname")) {
      // session中未存社区信息，调用delivery/commOne接口选择地址列表第一条数据作为默认信息
      let _this = this;
      this.$axios({
        method: "get",
        url: "http://47.104.186.142:80/delivery/commOne"
      }).then(res => {
        _this.community_name = res.data.data.name;
        _this.point_name = res.data.data.points[0].point_name;
        _this.point_address = res.data.data.points[0].point_address;

        // 判断用户是否第一次登陆，如果第一次登陆显示地址弹框让其输入
        this.$axios({
          method: "get",
          url: "http://47.104.186.142:80/user/show",
          params: {
            id: localStorage.getItem("setUserId"), //传的参数是用户的userId
            cname: _this.community_name //传的参数是用户选择的社区名community_name
          }
        }).then(res => {
          // alert(res.data.data.show);
          // show=0 不弹框，回显数据库信息；
          // show=1 弹框，让用户输入地址信息
          _this.showUserModal = res.data.data.show;

          if (_this.showUserModal == 1) {
            _this.showModal = true;
          } else if (_this.showUserModal == 0) {
            // console.log("用户信息已经存在,不弹编辑框，用户信息回显到界面")
            // 请求后台用户的数据queryUserById接口
            this.$axios({
              method: "get",
              url: "http://47.104.186.142:80/user/queryUserById",
              params: {
                cname: _this.community_name, // 传的参数社区的名称
                id: localStorage.getItem("setUserId") //传的参数是用户UserId
              }
            }).then(res => {
              _this.userAddress = res.data;

              // 从后台获取到用户的数据，简化名称方便后续数据绑定
              _this.roomNo = _this.userAddress.data.room_number;
              _this.consignee = _this.userAddress.data.consignee;
              _this.phone = _this.userAddress.data.phone_number;

              // 临时存储在initForm表单中作为记录
              this.initForm = {
                roomNo: _this.userAddress.data.room_number,
                consignee: _this.userAddress.data.consignee,
                phone: _this.userAddress.data.phone_number
              };
            });
          }
        });
      });
    } else {
      // session存着该用户的所选的社区信息，调用show接口，查询存在的用户信息并回显到界面
      this.community_name = sessionStorage.getItem("setname");
      this.point_name = sessionStorage.getItem("setPointName");
      this.point_address = sessionStorage.getItem("setPointAddress");

      // 判断用户是否第一次登陆，如果第一次登陆显示地址弹框让其输入
      let _this = this;
      this.$axios({
        method: "get",
        url: "http://47.104.186.142:80/user/show",
        params: {
          id: localStorage.getItem("setUserId"), //传的参数是用户的userId
          cname: sessionStorage.getItem("setname") //传的参数是用户选择的社区名community_name
        }
      }).then(res => {
        //alert(res.data.data.show);
        // show=0 不弹框，回显数据库信息；
        // show=1 弹框，让用户输入地址信息
        _this.showUserModal = res.data.data.show;

        if (_this.showUserModal == 1) {
          _this.showModal = true;
        } else if (_this.showUserModal == 0) {
          // console.log("用户信息已经存在,不弹编辑框，用户信息回显到界面")
          // 请求后台用户的数据queryUserById接口
          this.$axios({
            method: "get",
            url: "http://47.104.186.142:80/user/queryUserById",
            params: {
              cname: sessionStorage.getItem("setname"), //传的参数是用户选择的社区名
              id: localStorage.getItem("setUserId") //传的参数是用户userId
            }
          }).then(res => {
            _this.userAddress = res.data;

            // 从后台获取到用户的数据，简化名称方便后续数据绑定
            _this.roomNo = _this.userAddress.data.room_number;
            _this.consignee = _this.userAddress.data.consignee;
            _this.phone = _this.userAddress.data.phone_number;

            // 临时存储在initForm表单中作为记录
            this.initForm = {
              roomNo: _this.userAddress.data.room_number,
              consignee: _this.userAddress.data.consignee,
              phone: _this.userAddress.data.phone_number
            };
          });
        }
      });
    }
  },
  methods: {
    checkShowModal() {
      this.showModal2 = false;
      if (this.showModal2Type == "showModal1") {
        this.showModal = true;
      }
    },
    gotoPay() {
      if (!this.roomNo) {
        this.showModal2 = true;
        this.message = "请输入房间号！";
        this.showModal2Type = "showModal1";
      } else if (!this.consignee) {
        this.showModal2 = true;
        this.message = "请输入收货人！";
        this.showModal2Type = "showModal1";
      } else if (!this.phone) {
        this.showModal2 = true;
        this.message = "请输入联系电话！";
        this.showModal2Type = "showModal1";
      } else if (
        !/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/.test(
          this.phone
        )
      ) {
        this.showModal2 = true;
        this.message = "手机号格式不正确，请重新输入！";
        this.showModal2Type = "showModal1";
      } else {
        // 跳转创建订单，微信支付操作流程
        if (Bus.order) {
          // 定义新数组Menus存储后台需要的信息
          let menusArr = [];
          Bus.order.map((item, index) => {
            menusArr.push(
              Object.assign({ menu_id: item.id, amount: item.number })
            );
          });

          this.$axios({
            method: "post",
            url: "http://47.104.186.142:80/order/creatOrder",
            data: {
              community: this.community_name,
              point: this.point_name,
              point_address: this.point_address,
              discount: 0.0,
              room_num: this.roomNo,
              delivery_name: this.consignee,
              delivery_tel: this.phone,
              payment: this.totlePriceTemp,
              user_id: localStorage.getItem("setUserId"),
              open_id: localStorage.getItem("setOpenId"),
              cookbook_id: localStorage.getItem("setMenuDetailId"),
              menus: menusArr
            }
          }).then(res => {
            //alert(res.data.message)
            //console.log(res.data.data);
            this.order_num = res.data.data.order_num;
            localStorage.setItem("setOrderNum", this.order_num);

            let vm = this;
            WeixinJSBridge.invoke(
              "getBrandWCPayRequest",
              {
                appId: res.data.data.appId, //公众号名称，由商户传入
                timeStamp: res.data.data.timeStamp, //时间戳，自1970年以来的秒数
                nonceStr: res.data.data.nonceStr, //随机串
                package: res.data.data.package, // prepay_id
                signType: res.data.data.signType, //微信签名方式：
                paySign: res.data.data.paySign //微信签名
              },
              function(res) {
                if (res.err_msg == "get_brand_wcpay_request:ok") {
                  vm.$router.push("/payFinish"); // 支付成功跳转订单页面
                } else {
                  alert("支付失败，请重试！");
                }
              }
            );
          });
        }
      }
    },
    cancelAddress() {
      //取消按钮操作，获取之前initForm表单存储的数据
      this.showModal = false;
    },
    submitAddress() {
      // 确定按钮操作，由于双向数据绑定用户数据会同步更新
      if (!this.roomNo) {
        this.showModal2 = true;
        this.message = "请输入房间号！";
        this.showModal2Type = "showModal1";
      } else if (!this.consignee) {
        this.showModal2 = true;
        this.message = "请输入收货人！";
        this.showModal2Type = "showModal1";
      } else if (!this.phone) {
        this.showModal2 = true;
        this.message = "请输入联系电话！";
        this.showModal2Type = "showModal1";
      } else if (
        !/^((1[3,5,8][0-9])|(14[5,7])|(17[0,6,7,8])|(19[7]))\d{8}$/.test(
          this.phone
        )
      ) {
        this.showModal2 = true;
        this.message = "手机号格式不正确，请重新输入！";
        this.showModal2Type = "showModal1";
      } else if (this.showUserModal == 1) {
        // 用户第一次登陆填好信息后，存到后台
        let _this = this;
        this.$axios({
          method: "post",
          url: "http://47.104.186.142:80/user/addAddress",
          params: {
            id: localStorage.getItem("setUserId") //传的参数是UserId
          },
          data: {
            room_number: this.roomNo,
            consignee: this.consignee,
            phone_number: this.phone,
            pname: this.point_name,
            point_address: this.point_address,
            cname: this.community_name
          }
        }).then(res => {
          //console.log(res)
          if (res.data.code == 0) {
            //返回code等于0，点击确定数据库保存成功
            this.showModal = false;
          } else {
            this.showModal2 = true;
            this.message = "信息保存失败，请重试！";
            this.showModal2Type = "showModal1No";
          }
        });
      } else if (this.showUserModal == 0) {
        // 用户不是第一次登陆，信息会回显在界面，点击编辑输入用户信息，执行Update接口
        let _this = this;
        this.$axios({
          method: "post",
          url: "http://47.104.186.142:80/user/updateById",
          params: {
            id: localStorage.getItem("setUserId") //传的参数是UserId
          },
          data: {
            room_number: this.roomNo,
            consignee: this.consignee,
            phone_number: this.phone,
            cname: this.community_name,
            pname: this.point_name,
            point_address: this.point_address
          }
        }).then(res => {
          //console.log(res.status)
          if (res.status == 200) {
            this.showModal = false;
          } else {
            this.showModal2 = true;
            this.message = "信息保存失败，请重试！";
            this.showModal2Type = "showModal1No";
          }
        });
      }
    }
  }
};
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
@import '~commom/stylus/mixin';

.container {
    padding-bottom: 50px;

    .use-address {
        padding: 0 15px;
        background-color: #fffbf5;
        overflow: hidden;

        .header {
            display: flex;
            align-items: center;
            height: 49px;
            border-bottom: 1px solid #eee;
            justify-content: space-between;

            .left {
                font-size: 15px;
                color: #333333;
                font-weight: bold;
            }

            .right {
                color: #f20c00;
                display: flex;
                align-items: center;
                extent-click();

                .iconfont {
                    font-size: 20px;
                    font-weight: bold;
                    margin-right: 5px;
                }

                .text {
                    font-size: 12px;
                }
            }
        }

        .address {
            display: flex;
            margin: 20px 0 22.5px;

            .iconfont {
                color: #f7605e;
                font-size: 18px;
                margin-right: 15px;
            }

            .text {
                line-height: 20px;
                color: #333333;
                font-size: 14px;
            }
        }

        .user {
            display: flex;
            margin: 22.5px 0 20px;

            .iconfont {
                color: #f7605e;
                font-size: 18px;
                margin-right: 15px;
            }

            span {
                line-height: 20px;
                color: #333333;
                font-size: 14px;

                &.phone {
                    margin-left: 15px;
                }
            }
        }
    }

    .goods-detail {
        .header {
            line-height: 53px;
            color: #333333;
            font-size: 15px;
            font-weight: bold;
            padding: 0 15px;
        }

        .goods-content {
            padding: 0 15px;
            background-color: #f7f7f7;
            overflow: hidden;

            .good {
                padding: 10px 0;
                display: flex;
                border-bottom: 1px solid #eee;

                .img {
                    flex: 0 0 105px;
                    width: 105px;
                    height: 70px;
                    margin-right: 15px;
                }

                .content {
                    flex: 1;

                    .title {
                        color: #333;
                        font-size: 15px;
                        font-weight: bold;
                    }

                    .describe {
                        color: #666;
                        font-size: 13px;
                        line-height: 16px;
                        height: 32px;
                        line-hidden(2);
                        margin: 5px 0;
                    }

                    .price-number {
                        display: flex;
                        justify-content: space-between;
                        align-items: center;

                        .price {
                            color: #f20c00;
                            font-size: 12px;
                        }

                        .number {
                            font-size: 13px;
                            color: #333333;
                        }
                    }
                }
            }
        }

        .goods-footer {
            height: 49px;
            padding: 0 15px;
            background-color: #f7f7f7;
            display: flex;
            justify-content: space-between;
            align-items: center;

            .discount-price {
                font-size: 14px;
                color: #333333;
            }

            .discount-coupon {
                font-size: 12px;
                color: #f20c00;

                .iconfont {
                    color: #666666;
                    font-size: 12px;
                }
            }
        }
    }

    .footer {
        position: fixed;
        bottom: 0;
        left: 0;
        right: 0;
        height: 50px;
        line-height: 50px;
        display: flex;
        color: #ffffff;
        font-size: 15px;

        .totle {
            flex: 1;
            background-color: #333333;
            font-weight: bold;
            padding-left: 15px;
        }

        .ordering {
            flex: 0 0 118px;
            text-align: center;
            background-color: #f20c00;
        }
    }

    .modal {
        .modal-title {
            font-size: 15px;
            color: #333333;
            text-align: center;
            line-height: 20px;
            margin: -5px 0;
        }

        .modal-center {
            .form-group {
                display: flex;
                align-items: center;
                overflow: hidden;
                margin-bottom: 15px;

                label {
                    font-size: 14px;
                    color: #333333;
                    flex: 0 0 70px;
                }

                input {
                    font-size: 14px;
                    color: #555;
                    flex: 1;
                    border: none;
                    outline: none;
                    border-radius: 3px;
                    background-color: #f7f7f7;
                    height: 35px;
                    line-height: 35px;
                    padding: 0 5px;
                    overflow: hidden;

                    &:focus {
                        border: 1px solid #dcb67a;
                    }
                }

                input[disabled] {
                    color: #000;
                }
            }
        }

        .modal-foot {
            display: flex;
            justify-content: space-around;

            .btn {
                height: 30px;
                width: 91px;
                text-align: center;
                border: none;
                outline: none;
                border-radius: 20px;
                font-size: 13px;

                &.button-cancel {
                    background-color: #ffffff;
                    color: #333333;
                    border: 1px solid #333333;
                }

                &.button-submit {
                    background-color: #f20c00;
                    color: #ffffff;
                }
            }
        }
    }
}

.modal {
    .modal-default-button {
        float: right;
        color: #fff;
        background-color: #4aae9b;
        border: 1px solid #4aae9b;
        border-radius: 2px;
        padding: 6px 12px;
        background-color: #4dae9b;
        extent-click();
    }
}
</style>